<?php
namespace app\common\model;
use think\Model;
use think\Db;

class Base extends Model
{
	/**
     * 写入数据
     * @param array      $data  数据数组
     * @param array|true $field 允许字段
     * @return $array
     */
    public static function add($data = [], $allow = false)
    {
        $model = new static();
        $model->allowField($allow);
        // if (!empty($field)) {
        //     $model->allowField($field);
        // }
        if (empty($data['add_time'])) {
            $data['add_time'] = time();
        }
        if ($model->isUpdate(false)->save($data)) {
        	return ['code' => 1, 'msg' => '保存成功','data'=>$model];
        } else {
        	return ['code' => 0, 'msg' => '保存失败'];
        }
    }
    /**
     * 重写Model更新方法
     * @param array $data
     * @param array $where
     * @param null $field
     * @return bool
     */
    public static function update($data = [], $where = [], $field = null)
    {
        
        $model = new static();
        if (!empty($field)) {
            $model->allowField($field);
        }
        if ($model->isUpdate(true)->save($data, $where)) {            
            return ['code' => 1, 'msg' => '修改成功'];
        } else {
            return ['code' => 0, 'msg' => '修改失败'];
        }
    }
    public static function getByPage($page=1,$page_size=10)
    {
    	$model = new static();
        $total = $model->count();
    	$rows = $model->page($page, $page_size)->select();

        return [
            'rows'      => $rows,
            'total'     => $total,
            'page_size' => $page_size,
            'page'      => $page
        ];
    }
    public static function getMap($data, $field, $with='')
    {
        $model = new static();
        $field_vals = array_column($data, $field);

        $map_data = [];
        if ($with) {
            $rows = $model->with($with)->where('id', 'in', $field_vals)->select();

            foreach ($rows as $key => $row) {
                $map_data[$row['id']] = $row;
            }
        } else {
            $map_data = $model->where('id', 'in', $field_vals)->column('');
        }
        
        return $map_data;
    }
    public function getRelationInfo(array &$rows, $tb, $fk)
    {
        if (empty($rows)) {
            return [];
        }

        $pk = [];
        foreach ($rows as $row) {
            $pk[] = $row[$fk];
        }
        $pk = array_unique($pk);
        //print_r($pk);exit;
        $map_data = Db::name($tb)->where('id','in',$pk)->column('');
        //echo Db::getLastSql();
        return $map_data;
    }

}